<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有!                                |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: angl<anguolei@clcw.com.cn>                                     |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Broker;

/**
 * 经纪人类
 * Class Broker
 * @author angl
 */
class Broker
{
    private $aid = null;

    public function __construct($aid)
    {
        $this->aid = $aid;
    }

    /**
     * 添加经纪人
     * @param integer $uid
     * @param integer $superior_id
     * @return mixed
     */
    public static function create($uid, $superior_id = 0)
    {
        if ($uid < 1) {
            return false;
        }
        $data = [
            'uid' => $uid,
            'superior_id' => $superior_id,
            'invite_code' => gen_invite_code(),
            'create_time' => date('Y-m-d H:i:s')
        ];
        M()->startTrans();
        $aid = M('agent')->add($data);
        if ($aid < 1) {
            M()->rollback();
            return false;
        }
        $tid = M('agent_team')->add([
            'tid' => $aid,
            'create_time' => $data['create_time']
        ]);
        if ($tid < 1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $aid;
    }

    /**
     * 设置团队,无则增加,有不改
     * @param $tid
     * @return bool|mixed
     */
    public static function set_team($tid)
    {
        if (intval($tid) < 1) {
            return false;
        }
        $team = M('agent_team')->where("tid=" . $tid)->find();
        if (!empty($team)) {
            return $team['tid'];
        }
        $broker = M('agent')->where("aid=" . $tid)->find();
        $data = array(
            'tid' => $tid,
            'total_money' => $broker['total_money'],
            'create_time' => date('Y-m-d H:i:s', time())
        );
        return M('agent_team')->add($data);
    }

    /**
     * 获取记录详细信息
     * @return bool
     */
    public function detail()
    {
        if ($this->aid < 1) {
            return false;
        }
        $prefix = C("DB_PREFIX");
        return M('agent')->alias("ag")->field("u.uid,u.real_name,u.u_idcard,u.avatar,u.sms_mobile,ag.*")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where("ag.aid=" . $this->aid)->find();
    }

    /**
     * 获取今日统计
     * @param int $aid
     * @return array|bool
     */
    public static function get_today_money($aid)
    {
        if ($aid < 1) {
            return false;
        }
        //直接红包
        $today = date("Y-m-d");
        $map = [];
        $map['aid'] = $aid;
        $map['create_time'] = [['egt', $today . " 00:00:00"], ['elt', $today . " 23:59:59"]];
        $map['commission_type'] = [['eq', 1], ['eq', 2], ['eq', 4], 'or'];
        $direct = M('commission_log')->where($map)->sum('amount');
        $map['commission_type'] = ['eq', 3];
        $indirect = M('commission_log')->where($map)->sum('amount');
        //echo M()->getLastSql();
        $data = [
            'today_direct' => $direct > 0 ? number_format($direct, 2) : "0.00",
            'today_indirect' => $indirect ? number_format($indirect, 2) : '0.00'
        ];
        return $data;
    }

    /**
     * 获取详细信息
     * @param $params
     * @return bool
     */
    public static function get_detail_by_params($params)
    {
        if (empty($params)) {
            return false;
        }
        $map = array();
        if ((int)$params['uid'] > 0) {
            $map['u.uid'] = array('eq', (int)$params['uid']);
        }

        if ((int)$params['aid'] > 0) {
            $map['ag.aid'] = array('eq', (int)$params['aid']);
        }

        if ((int)$params['superior_id'] > 0) {
            $map['ag.superior_id'] = array('eq', (int)$params['superior_id']);
        }

        if (!empty($params['invite_code'])) {
            $map['ag.invite_code'] = array('eq', $params['invite_code']);
        }
        $prefix = C("DB_PREFIX");
        return M('agent')->alias("ag")->field("u.uid,u.avatar,u.real_name,u.pwd_mobile,u.sms_mobile,ag.*")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->find();
    }

    /**
     * 获取记录
     * @param $page
     * @param $page_size
     * @param int $uid
     * @param string $phone
     * @return array
     */
    public static function getList($page, $page_size, $uid = 0, $phone = '')
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 20 : (int)$page_size;
        $map = [];
        $map['u.status'] = 0;
        if ((int)$uid > 0) {
            $map['u.uid'] = ['eq', intval($uid)];
        }

        if (!empty($phone)) {
            $map['u.sms_mobile'] = ['eq', $phone];
        }

        $cols = "u.uid,u.avatar,u.real_name,u.sms_mobile,ag.*";
        $prefix = C('DB_PREFIX');
        $total = M('agent')->alias("ag")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->count();
        $list = M('agent')->alias("ag")->field($cols)
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->page($page)->limit($page_size)->order("u.uid DESC")->select();
        $sum = M('agent')->alias('ag')->field("SUM(ag.total_money) as total_amount,SUM(ag.wallet) as total_wallet")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->find();
        //echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'count' => $total,
            'sum' => $sum
        );
        return $result;
    }

    //经纪人列表
    public static function get_broker_list($page, $page_size, $params) 
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = array();
        /**
         * 搜索条件：1、个人ID 2、帐号 3、邀请人帐号 4、类型：顶级、非顶级 5、状态：启用、禁用 6、开始时间 7、结束时间
         */
        if($params['u_id']){
            $map['ag.uid'] = array('LIKE','%' .$params['u_id'] . '%');
        }   
        if($params['agent']){
            $map['u.pwd_mobile'] = array('like','%'.$params['agent'].'%');
        }   
        if($params['superior']){
            $superior = trim($params['superior']);
            $user = new \AuctionCore\Account\FrontUser();
            $info = $user->get_user_info_by_pwd_mobile($superior);
            if(!empty($info)){
                $agent_info = Broker::get_detail_by_uid($info['uid']);
                if(!empty($agent_info)){
                    $map['ag.superior_id'] = array('eq',$agent_info['aid']);
                }
            }
        }   
        if($params['agent_type']){
            $agent_type = $params['agent_type'];
            if($agent_type == 1){
                $map['superior_id']   = array('eq',0);
            }elseif($agent_type == 2){
                $map['superior_id']   = array('gt',0);
            }
        }
        if($params['agent_status']){
            $agent_status = $params['agent_status'];
            if($agent_status == 1){
                $map['u.status'] = array('eq',0);
            }elseif($agent_status == 2){
               $map['u.status'] = array('eq',1); 
            } 
        }
        if($params['start_time']){
            $map['ag.create_time'] = array('egt',$params['start_time'] . ' 00:00:00');
        }
        if($params['end_time']){
            $map['ag.create_time'] = array('elt',$params['end_time'] . ' 23:59:59');
        }   
        if($params['start_time'] && $params['end_time']){
            $map['ag.create_time'] = array(array('egt',$params['start_time'] . ' 00:00:00'),array('elt',$params['end_time'] . ' 23:59:59'));
        }
        $cols = "u.uid,u.real_name,u.sms_mobile,u.pwd_mobile,u.u_idcard,u.status,ag.*";
        $order = "ag.aid DESC";
        $prefix = C('DB_PREFIX');
        $total = M('agent')->alias("ag")
            ->join($prefix . "user AS u ON u.uid = ag.uid")
            ->where($map)->count();
        $list = M('agent')->alias("ag")->field($cols)
            ->join($prefix . "user AS u ON u.uid = ag.uid")
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        foreach($list as $k=>$v){
            if(!empty($v['superior_id'])){
                $uid = Broker::getDetailByAid($v['superior_id']);
                $user = new \AuctionCore\Account\FrontUser();
                $info = $user->get_user_info_by_uid($uid['uid']);
                $list[$k]['invite_people'] =  $info['pwd_mobile'];
                $list[$k]['agent_type'] = 2; //非顶级
            }else{
                $list[$k]['agent_type'] = 1; //顶级
            }
            $direct_broker_result = self::get_direct_broker_num($v['aid']);
            $list[$k]['direct_broker_num'] = $direct_broker_result['total'];
            $list[$k]['indirect_broker_num'] = self::get_indirect_broker_num($direct_broker_result['broker_list']);
            $list[$k]['my_customer_num'] = self::get_my_customer_num($v['uid']);
        }
        $result = array(
            'list' => $list,
            'total' => $total,
        );
        return $result;
    }
    
    /**
     * 计算直接经纪人数量
     * @param int $agent_id  
     */
    private static function get_direct_broker_num($agent_id)
    {
        $condition['superior_id'] = $agent_id;
        $broker_list = M('agent')->where($condition)->select();
        $result = array(
            'broker_list'=>$broker_list,
            'total'=> count($broker_list)
        );
        return $result;
    }
    /**
     * 计算间接经纪人数量
     * @param int $broker_list 
     */
    private static function get_indirect_broker_num($broker_list)
    {
        $num = 0;
        if(!empty($broker_list)){
            foreach($broker_list as $bl){
                $map['superior_id'] = $bl['aid'];
                $indirect_broker_list = M('agent')->where($map)->select();
                $indirect_num = 0;
                if(empty($indirect_broker_list)){
                    continue;
                }
                $indirect_num = count($indirect_broker_list);
                $indirect_num = $indirect_num + self::get_indirect_broker_num($indirect_broker_list);
                $num = $num + $indirect_num;
            }
        }
        return $num;
    }
    /**
     * 计算我的客户数量
     * @param int $uid 
     */
    private static function get_my_customer_num($uid)
    {
        $condition['uid'] = $uid;
        $total = M('my_customer')->where($condition)->count();
        return $total;
    }
    
    /**
     * 我的经纪人列表
     * @param $page
     * @param $page_size
     * @param $params
     * @return array
     */
    public static function getBrokerList($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 20 : (int)$page_size;
        $map = array();

        if ((int)$params['uid'] > 0) {
            $map['u.uid'] = array('eq', (int)$params['uid']);
        }

        if ((int)$params['aid'] > 0) {
            $map['ag.aid'] = array('eq', (int)$params['aid']);
        }

        if ((int)$params['superior_id'] > 0) {
            $map['ag.superior_id'] = array('eq', (int)$params['superior_id']);
        }

        if ((int)$params['ur_uid'] > 1) {
            $ur_uid = (int)$params['ur_uid'];
        }

        $cols = "u.uid,u.avatar,u.real_name,u.sms_mobile,ag.*,ur.remark remark_name";
        $prefix = C('DB_PREFIX');
        $total = M('user')->alias("u")
            ->join($prefix . "agent AS ag  ON ag.uid=u.uid")
            ->join("LEFT JOIN " . $prefix . "user_remark AS ur ON ur.remark_id=ag.aid and ur.remark_type=1 and ur.uid=$ur_uid")
            ->where($map)->count();
        $list = M('user')->alias("u")->field($cols)
            ->join($prefix . "agent AS ag  ON ag.uid=u.uid")
            ->join("LEFT JOIN " . $prefix . "user_remark AS ur ON ur.remark_id=ag.aid and ur.remark_type=1 and ur.uid=$ur_uid")
            ->where($map)->page($page)->limit($page_size)->select();

        $result = array(
            'list' => $list,
            'count' => $total,
        );
        return $result;
    }

    /**
     * 获取个人按天记录
     * @param int $page
     * @param int $page_size
     * @param array $params
     * @param string $order
     * @return array
     */
    public static function get_personal_list($page = 1, $page_size = 20, $params = array(), $order = "date desc")
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 10 : (int)$page_size;
        $map = array();
        if ($params['aid'] > 1) {
            $map['aid'] = array('eq', $params['aid']);
        }
        //上级id 即团队id
        if ($params['superior_id'] > 1) {
            $map['superior_id'] = array('eq', $params['superior_id']);
        }
        //日期
        if (!empty($params['date'])) {
            $map['date'] = array('eq', $params['date']);
        }
        //按日期筛选
        if (!empty($params['start_day']) || !empty($params['end_day'])) {
            if (empty($params['start_day'])) {
                $map['date'] = array("elt", $params['end_day']);
            } elseif (empty($params['end_day'])) {
                $map['date'] = array("egt", $params['start_day']);
            } else {
                $map['date'] = array(array("egt", $params['start_day']), array("lt", $params['end_day']));
            }
        }

        $total = M('personal_daily_income')->where($map)->count();
        $list = M('personal_daily_income')->where($map)
            ->page($page)->limit($page_size)->order($order)->select();
        return array(
            'total' => $total,
            'list' => $list,
        );
    }

    /**
     * 获取团队列表
     * @param int $page
     * @param int $page_size
     * @param array $params
     * @param string $order
     * @return array
     */
    public static function get_team_member_list($page = 1, $page_size = 20, $params = array(), $order = "date desc")
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 10 : (int)$page_size;
        $map = array();

        //上级id 即团队id
        if ($params['superior_id'] > 0) {
            $map['pdi.superior_id'] = array('eq', $params['superior_id']);
        }

        //日期
        if (!empty($params['date'])) {
            $map['pdi.date'] = array('eq', $params['date']);
        }

        $prefix = C('DB_PREFIX');
        $total = M('personal_daily_income')->alias('pdi')
            ->join($prefix . "agent as ag ON ag.aid=pdi.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->count();

        $list = M('personal_daily_income')->alias('pdi')->field('u.sms_mobile,u.uid,u.avatar,pdi.*')
            ->join($prefix . "agent as ag ON ag.aid=pdi.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->page($page)->limit($page_size)->order($order)->select();

        return array(
            'total' => $total,
            'list' => $list,
        );

    }

    /**
     * 获取个人总金额
     * @param $aid
     * @return bool|mixed
     */
    public static function get_personal_total($aid)
    {
        if ($aid < 1) {
            return false;
        }
        return M('agent')->field('develop_deal+direct_deal+indirect_deal as total_money')->where("aid = " . $aid)->find();
    }

    /**
     * 获取团队按日记录列表
     * @param int $page
     * @param int $page_size
     * @param array $params
     * @param string $order
     * @return array
     */
    public static function get_team_list($page = 1, $page_size = 20, $params = array(), $order = "date desc")
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 10 : (int)$page_size;
        $map = array();
        $map['tid'] = array('eq', $params['tid']);

        //按日期筛选
        if (!empty($params['start_day']) || !empty($params['end_day'])) {
            if (empty($params['start_day'])) {
                $map['date'] = array("elt", $params['end_day']);
            } elseif (empty($params['end_day'])) {
                $map['date'] = array("egt", $params['start_day']);
            } else {
                $map['date'] = array(array("egt", $params['start_day']), array("lt", $params['end_day']));
            }
        }
        $total = M('team_daily_income')->where($map)->count();
        $list = M('team_daily_income')->where($map)->page($page)->limit($page_size)->order($order)->select();
        return array(
            'total' => $total,
            'list' => $list,
        );
    }

    /**
     * 获取团队收益总额
     * @param $tid
     * @return bool|mixed
     */
    public static function get_team_total($tid)
    {
        if ($tid < 1) {
            return false;
        }
        return M('agent_team')->field('total_money')->where("tid = " . $tid)->find();
    }

    /**
     * 获取个人统计
     * @param $aid
     * @return array|bool
     */
    public static function get_personal_stat($aid)
    {
        if ($aid < 1) {
            return false;
        }
        $map = array();
        //经纪人ID
        $map['aid'] = array('eq', $aid);
        //昨日统计
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $map['date'] = array('eq', $yesterday);
        $yest_data = M('personal_daily_income')->where($map)->find();
        //累积总额
        $accumulate = M('agent')->field('total_money')->where("aid=$aid")->find();
        if (empty($yest_data) && $accumulate['total_money'] == 0) {
            return array();
        }
        $data = array(
            'yesterday' => $yest_data,
            'all' => $accumulate,
        );
        return $data;
    }

    /**
     * 获取团队统计
     * @param $tid
     * @return array|bool
     */
    public static function get_teams_stat($tid)
    {
        if ($tid < 1) {
            return false;
        }

        $map = array();
        //团队id,即头领的aid
        $map['tid'] = $tid;
        //昨日收益
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $map['date'] = array('eq', $yesterday);
        $yest_data = M('team_daily_income')->where($map)->find();

        $accumulate = M('agent_team')->where("tid=$tid")->find();
        $data = array(
            'yesterday' => $yest_data,
            'all' => $accumulate,
        );
        return $data;
    }

    /**
     * @param $uid
     * @param $remark_uid
     * @param int $type
     * @return bool|mixed
     */
    public static function get_remark_name($uid, $remark_id, $type)
    {
        if ($uid < 1 || $remark_id < 1 || $type < 1) {
            return false;
        }
        $map = array(
            'uid' => $uid,
            'remark_id' => $remark_id,
            'remark_type' => $type,
        );
        return M('user_remark')->where($map)->find();
    }

    /**
     * 获取个人每日详细记录
     * @param int $page
     * @param $page_size
     * @param array $params
     * @return array
     */
    public static function get_commission_log($page = 1, $page_size, $params = array())
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 10 : (int)$page_size;

        $map = array();
        $map['cl.type'] = ['eq', 1];
        $map['cl.aid'] = ['eq', $params['aid']];

        if (!empty($params['day'])) {
            $map['cl.create_time'] = array(array('egt', $params['day'] . " 00:00:00"), array('elt', $params['day'] . " 23:59:59"));
        }
        $prefix = C("DB_PREFIX");
        $fields = "cl.commission_type,cl.create_time,cl.amount,u.pwd_mobile as mobile";
        $total = M('commission_log')->alias("cl")
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->where($map)->count();
        $list = M('commission_log')->alias("cl")->field($fields)
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->where($map)->page($page)->limit($page_size)->order('cl.create_time desc')->select();

        return array(
            'total' => $total,
            'list' => $list,
        );
    }

    /**
     * 获取佣金详细记录
     * @param int $page
     * @param int $page_size
     * @param $aid
     * @param int $type
     * @param string $start_time
     * @param string $end_time
     * @return array
     */
    public static function getBrokerCommissionList($page = 1, $page_size = 20, $aid, $type = 0, $start_time = '', $end_time = '')
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 10 : (int)$page_size;

        $map = array();
        $map['cl.type'] = ['eq', 1];
        $map['cl.aid'] = ['eq', $aid];

        //红包类型
        if($type==1){//直接红包
            $map['commission_type'] = [['eq',1],['eq',2],['eq',4],'or'];
        }elseif($type==2){ //间接红包
            $map['commission_type'] = ['eq',3];
        }else{
            $map['commission_type'] = ['neq',5];
        }
        //发生时间
        if (!empty($start_time) && !empty($end_time)) {
            $map['cl.create_time'] = [['egt', $start_time], ['elt', $end_time]];
        } elseif (!empty($start_time) && empty($end_time)) {
            $map['cl.create_time'] = [['egt', $start_time]];
        } elseif (!empty($end_time) && empty($start_time)) {
            $map['cl.create_time'] = ['elt', $end_time];
        }

        $prefix = C("DB_PREFIX");
        $fields = "cl.commission_type,cl.create_time,cl.amount,u.pwd_mobile as mobile";
        $total = M('commission_log')->alias("cl")
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->where($map)->count();
        $list = M('commission_log')->alias("cl")->field($fields)
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->where($map)->page($page)->limit($page_size)->order('cl.create_time desc')->select();

        return array(
            'total' => $total,
            'list' => $list,
        );
    }


    /**
     * 获取个人收益记录
     * @param $aid
     * @param $day
     * @param int $superior_id
     * @return bool
     */
    public static function get_personal_income($aid, $day, $superior_id = 0)
    {
        if (intval($aid) < 1 || empty($day)) {
            return false;
        }
        $map = array();
        $map['pdi.aid'] = array('eq', $aid);
        $map['pdi.date'] = array('eq', $day);
        if (intval($superior_id) > 0) {
            $map['superior_id'] = $superior_id;
        }

        $prefix = C('DB_PREFIX');
        $data = M('personal_daily_income')->alias('pdi')->field('u.sms_mobile,u.uid,u.avatar,pdi.*')
            ->join($prefix . "agent AS ag ON ag.aid=pdi.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")->where($map)->find();
        return $data;
    }

    /**
     * 新增提现记录
     * @param $aid
     * @param $amount
     * @param $bank
     * @param $card_no
     * @return bool|mixed
     */
    public static function add_withdraw($aid, $amount, $bank, $card_no)
    {
        if (intval($aid) < 1 || empty($amount) || empty($bank) || empty($card_no)) {
            return false;
        }
        //启动事务
        M()->startTrans();
        //从钱包中去掉取的金额
        $res = M('agent')->where("aid=$aid")->setDec('wallet', $amount);
        //取现记录
        $cl_id = M('commission_log')->add([
            'aid' => $aid,
            'type' => 2,
            'amount' => $amount,
            'create_time' => date('Y-m-d H:i:s', time())
        ]);
        $id = M('withdrawal_log')->add([
            'cl_id' => $cl_id,
            'aid' => $aid,
            'amount' => $amount,
            'bank_name' => $bank,
            'card_no' => $card_no,
            'create_time' => date('Y-m-d H:i:s', time())
        ]);
        if (!$res || $cl_id < 1 || $id < 1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return $id;
    }


    /**
     * 零钱明细列表
     * @param int $page
     * @param $page_size
     * @param array $params
     * @return array|bool
     */
    public function record_list($page = 1, $page_size, $params = array())
    {
        if ($this->aid < 1) {
            return false;
        }
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 20 : (int)$page_size;

        $map = array();
        $map['cl.aid'] = array('eq', $this->aid);
        //类型1收入2支出
        if (intval($params['type']) > 0) {
            $map['cl.type'] = ['eq', intval($params['type'])];
        }

        $prefix = C("DB_PREFIX");
        $fields = "cl.aid,cl.type,cl.amount,cl.commission_type,wl.bank_name,cl.create_time,wl.card_no,wl.result,wl.remark,u.pwd_mobile as mobile";
        $total = M('commission_log')->alias('cl')
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->join("LEFT JOIN {$prefix}withdrawal_log as wl ON cl.id=wl.cl_id")
            ->where($map)->count();

        $list = M('commission_log')->alias('cl')->field($fields)
            ->join("LEFT JOIN " . $prefix . "agent as a ON a.aid=cl.other_aid")
            ->join("LEFT JOIN " . $prefix . "user as u On u.uid=a.uid")
            ->join("LEFT JOIN {$prefix}withdrawal_log as wl ON cl.id=wl.cl_id")
            ->where($map)->page($page)->limit($page_size)->order("cl.create_time desc")->select();
        //echo M()->getLastSql();exit;
        return array(
            'total' => $total,
            'list' => $list,
        );
    }

    /**
     * 提现申请列表
     * @param int $page
     * @param $page_size
     * @param array $params
     * @return array|bool
     */
    public function withdraw_list($page = 1, $page_size, $params = array())
    {
        if ($this->aid < 1) {
            return false;
        }
        $page = (int)$page < 1 ? 1 : (int)$page;
        $page_size = (int)$page_size < 1 ? 20 : (int)$page_size;

        $map = array();
        $map['aid'] = array('eq', $this->aid);

        if ($params['result'] > -1) {
            $map['result'] = ['eq', (int)$params['result']];
        }

        $total = M('withdrawal_log')->where($map)->count();
        $list = M('withdrawal_log')
            ->where($map)
            ->page($page)
            ->limit($page_size)
            ->order("create_time DESC")
            ->select();

        return array(
            'total' => $total,
            'list' => $list,
        );
    }


    /**
     * 通过aid获取经纪人信息
     * @param $aid
     * @return bool|mixed
     */
    public static function getDetailByAid($aid)
    {
        if (intval($aid) < 1) {
            return false;
        }
        return M('agent')->where(['aid' => $aid])->find();
    }
    
    //根据uid获取经纪人信息
    public static function get_detail_by_uid($uid) {
        if (intval($uid) < 1) {
            return false;
        }
        return M('agent')->where(['uid' => $uid])->find();
    }

    /**
     * 通过邀请码获取经纪人信息
     * @param string $invite_code 邀请码
     * @return bool|mixed
     */
    public static function get_detail_by_invite_code($invite_code)
    {
        if (empty($invite_code)) {
            return false;
        }
        return M('agent')->where(['invite_code' => $invite_code])->find();
    }

    /**
     * 获取取现列表 运营平台
     * @param int $page
     * @param int $pageSize
     * @param int $uid
     * @param string $phone
     * @return array
     */
    public static function getWithdrawList($page = 1, $pageSize = 10, $result = 0, $uid = 0, $phone = '', $real_name = '', $id_card = '', $start_time = '', $end_time = '')
    {
        $page = $page < 1 ? 1 : (int)$page;
        $pageSize = $pageSize < 1 ? 20 : (int)$pageSize;
        $map = [];
        if($result!=1){
            $map['u.status'] = 0;
        }
        $map['wl.result'] = (int)$result;
        //个人uid
        if ((int)$uid > 0) {
            $map['u.uid'] = ['eq', intval($uid)];
        }
        //账号即手机号
        if (!empty($phone)) {
            $map['u.sms_mobile'] = ['eq', trim($phone)];
        }
        //姓名
        if (!empty($real_name)) {
            $map['u.real_name'] = ['like', "%" . trim($real_name) . "%"];
        }
        //身份证
        if (!empty($id_card)) {
            $map['u.u_idcard'] = ['eq', trim($id_card)];
        }

        $time_field = $result>0 ? 'wl.last_update' : 'wl.create_time' ;
        //发生时间
        if(!empty($start_time) && !empty($end_time) ){
            $map[$time_field] = [['egt',$start_time],['elt',$end_time . " 23:59:59"]];
        } elseif (!empty($start_time) && empty($end_time)){
            $map[$time_field] = [['egt',$start_time]];
        } elseif (!empty($end_time) && empty($start_time)){
            $map[$time_field] = ['elt',$end_time . " 23:59:59"];
        }
        
        $cols = "u.uid,u.real_name,u.sms_mobile,u.u_idcard,wl.*";
        $prefix = C('DB_PREFIX');
        $total = M('withdrawal_log')->alias("wl")
            ->join($prefix . "agent AS ag ON wl.aid=ag.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->count();
        $list = M('withdrawal_log')->alias("wl")->field($cols)
            ->join($prefix . "agent AS ag ON wl.aid=ag.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->page($page)->limit($pageSize)->order("wl.create_time desc")->select();
        $sum = M('withdrawal_log')->alias("wl")->field("SUM(wl.amount) as total_amount")
            ->join($prefix . "agent AS ag ON wl.aid=ag.aid")
            ->join($prefix . "user AS u ON u.uid=ag.uid")
            ->where($map)->find();
        //echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'count' => $total,
            'sum' => $sum
        );
        return $result;
    }

    /**
     * 获取取现信息
     * @param $id
     * @return bool|mixed
     */
    public static function getWithdrawInfoById($id)
    {
        if ((int)$id < 1) {
            return false;
        }
        return M('withdrawal_log')->where("id=$id")->find();
    }

    /**
     * 更新提现记录by
     * @param $id
     * @param $data
     * @return bool
     */
    public static function upWithdrawById($id, $data)
    {
        if ($id < 1 || empty($data)) {
            return false;
        }
        return M('withdrawal_log')->where("id=$id")->save($data);
    }

    /**
     * 更新经纪人零钱
     * @param $aid
     * @param $amount
     * @return bool
     */
    public static function upWalletByAid($aid, $amount)
    {
        if ((int)$aid < 1 || $amount <= 0) {
            return false;
        }
        return M('agent')->where("aid={$aid}")->setInc('wallet', $amount);
    }

    /**
     * 批量提现成功
     * @param array $ids
     * @param array $data
     * @return bool
     */
    public static function batchWithdrawByIds($ids,$data)
    {
        if(empty($ids) || empty($data)){
            return false;
        }
        return M('withdrawal_log')->where(['id'=>['in',$ids]])->data($data)->save();
    }
}